package com.csdj.server.controller;

import com.csdj.server.pojo.Admin;
import com.csdj.server.pojo.RespBean;
import com.csdj.server.service.IAdminService;
import com.csdj.server.utils.FastDFSClient;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;

/**
 * @ClassName: AdminInfoController
 * @Author: ZouLi
 * @Description:
 * @Date: 2023/1/12 13:37
 **/
@RestController
public class AdminInfoController {
    @Autowired
    private IAdminService adminService;

    @ApiOperation(value = "更新当前用户信息")
    @PutMapping("/admin/info")
    public RespBean updateAdminInfo(@RequestBody Admin admin, Authentication authentication){
        // 如果更新成功 则修改authentication
        if (adminService.updateById(admin)) {
            SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(
                    admin,
                    authentication.getCredentials(),
                    authentication.getAuthorities()));
            return RespBean.success("修改成功！");
        }
        return RespBean.error("修改失败！");
    }

    @ApiOperation(value = "修改密码")
    @PutMapping("/admin/pass")
    public RespBean updatePassword(@RequestBody Map<String,Object> info){
        String oldPass = (String) info.get("oldPass");
        String pass = (String) info.get("pass");
        Integer adminId = (Integer) info.get("adminId");
        return adminService.updatePassword(oldPass, pass, adminId);
    }

    @ApiOperation(value = "修改用户头像")
    @ApiImplicitParams({@ApiImplicitParam(name = "file", value = "头像", dataType = "MultipartFile")})
    @PostMapping("/admin/userface")
    public RespBean updateUserFace(MultipartFile file, Integer id, Authentication authentication){
        // 上传文件返回文件地址
        String[] res = FastDFSClient.uploadFile(file);
        String url = "";
        try {
            url = FastDFSClient.getFilePath() + res[0] +"/"+res[1];
        } catch (Exception e) {
            e.printStackTrace();
        }
        return adminService.updateAdminUserFace(url, id, authentication);
    }

}
